# -*- coding: utf-8 -*-

import sqlite3
import time

from . import config
from . import user

class Article:

    def __init__(self, aid=None):
        self.aid = aid
        self.title = None
        self.content = None
        self.author_id = None
        self.author_name = None
        self.last_time = None
        if aid:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE aid = ?;""",
                        (aid, )).fetchone()
                if data:
                    self.aid = data[0]
                    self.title = data[1]
                    self.content = data[2]
                    self.author_id = data[3]
                    self.author_name = data[4]
                    self.last_time = data[5]
                else:
                    raise ValueError("wrong aid")

    @staticmethod
    def search(aid=None, title=None, content=None, author_id=None, author_name=None):
        if aid:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE aid = ? ORDER BY last_time DESC;""",
                        (aid, )).fetchall()
                if not data:
                    return []
                results = []
                for article in data:
                    _article = Article()
                    _article.aid = article[0]
                    _article.title = article[1]
                    _article.content = article[2]
                    _article.author_id = article[3]
                    _article.author_name = article[4]
                    _article.last_time = article[5]
                    results.append(_article)
                return results
        if title:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE title LIKE ? ORDER BY last_time DESC;""",
                        ("%"+title+"%", )).fetchall()
                if not data:
                    return []
                results = []
                for article in data:
                    _article = Article()
                    _article.aid = article[0]
                    _article.title = article[1]
                    _article.content = article[2]
                    _article.author_id = article[3]
                    _article.author_name = article[4]
                    _article.last_time = article[5]
                    results.append(_article)
                return results
        if content:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE content LIKE ? ORDER BY last_time DESC;""",
                        ("%"+content+"%", )).fetchall()
                if not data:
                    return []
                results = []
                for article in data:
                    _article = Article()
                    _article.aid = article[0]
                    _article.title = article[1]
                    _article.content = article[2]
                    _article.author_id = article[3]
                    _article.author_name = article[4]
                    _article.last_time = article[5]
                    results.append(_article)
                return results
        if author_id:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE author_id = ? ORDER BY last_time DESC;""",
                        ("%"+author_id+"%", )).fetchall()
                if not data:
                    return []
                results = []
                for article in data:
                    _article = Article()
                    _article.aid = article[0]
                    _article.title = article[1]
                    _article.content = article[2]
                    _article.author_id = article[3]
                    _article.author_name = article[4]
                    _article.last_time = article[5]
                    results.append(_article)
                return results
        if author_name:
            with sqlite3.connect(config.DATEBASE) as db:
                cur = db.cursor()
                data = cur.execute(
                    """SELECT * FROM articles WHERE author_name = ? ORDER BY last_time DESC;""",
                        ("%"+author_name+"%", )).fetchall()
                if not data:
                    return []
                results = []
                for article in data:
                    _article = Article()
                    _article.aid = article[0]
                    _article.title = article[1]
                    _article.content = article[2]
                    _article.author_id = article[3]
                    _article.author_name = article[4]
                    _article.last_time = article[5]
                    results.append(_article)
                return results

    def post(self):
        with sqlite3.connect(config.DATEBASE) as db:
            cur = db.cursor()
            if cur.execute(
                """SELECT aid FROM articles WHERE aid = ?;""",
                    (self.aid, )).fetchone():
                return False
            cur.execute(
                """INSERT INTO articles VALUES (?, ?, ?, ?, ?, ?);""",
                    (None, self.title, self.content,
                        self.author_id, self.author_name, int(time.time())))
            db.commit()
            self.aid = Article().search(title=self.title)[0].aid
            return True

    def reply(self, uid, content):
        try:
            _user = user.User(uid=uid)
        except:
            return False
        with sqlite3.connect(config.DATEBASE) as db:
            cur = db.cursor()
            if self.aid == None:
                return False
            cur.execute(
                """INSERT INTO replies VALUES (?, ?, ?, ?, ?, ?);""",
                    (None, self.aid, content,
                        uid, _user.name, int(time.time())))
            cur.execute(
                """UPDATE articles SET last_time = ? WHERE aid = ?;""",
                    (int(time.time()), self.aid))
            db.commit()
            return True


def article_list(page=1):
    offset = (page - 1) * 20
    with sqlite3.connect(config.DATEBASE) as db:
        cur = db.cursor()
        data = cur.execute(
            """SELECT * FROM articles ORDER BY last_time DESC LIMIT 20 OFFSET ?""",
                (offset, )).fetchall()
        results = []
        for art in data:
            _article = Article()
            _article.aid = art[0]
            _article.title = art[1]
            _article.content = art[2]
            _article.author_id = art[3]
            _article.author_name = art[4]
            _article.last_time = art[5]
            results.append(_article)
        return results


def relpy_list(aid, page=1):
    offset = (page - 1) * 20
    with sqlite3.connect(config.DATEBASE) as db:
        cur = db.cursor()
        data = cur.execute(
            """SELECT * FROM replies WHERE aid = ? LIMIT 20 OFFSET ?""",
                (aid, offset)).fetchall()
        return [{
            "rid": reply[0],
            "aid": reply[1],
            "content": reply[2],
            "author_id": reply[3],
            "author_name": reply[4],
            "time": reply[5]
        } for reply in data]
